package com.galaxy.device.config;

import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Elasticsearch配置类
 */
@Configuration
public class ElasticsearchConfig {

    @Value("${easy-es.address}")
    private String address;

    @Value("${easy-es.schema}")
    private String schema;

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        // 创建 RestClient
        RestClientBuilder restClient = RestClient.builder(
            new HttpHost(address.split(":")[0],
                Integer.parseInt(address.split(":")[1]),
                schema))
            .setRequestConfigCallback(requestConfigBuilder -> {
                requestConfigBuilder.setConnectTimeout(10000);  // 增加连接超时时间
                requestConfigBuilder.setSocketTimeout(10000);   // 增加套接字超时时间
                requestConfigBuilder.setConnectionRequestTimeout(10000);  // 增加连接请求超时时间
                return requestConfigBuilder;
            })
            .setHttpClientConfigCallback(httpClientBuilder -> {
                // 设置最大连接数
                httpClientBuilder.setMaxConnTotal(100);
                // 设置每个路由的最大连接数
                httpClientBuilder.setMaxConnPerRoute(100);
                return httpClientBuilder;
            });

        // 创建 RestHighLevelClient
        return new RestHighLevelClient(restClient);
    }
}
